var address = localStorage.address || '渋谷';

var shops = [];

var mc = new MyClassifier('foomoo');

var scores = [];

var ys = [];

window.addEventListener('load', function(e) {
	document.getElementById('address').value = address;

	document.getElementById('btnSearch').addEventListener('click', function(e) {
		var _address = document.getElementById('address').value;
		localStorage.address = _address;
		
		var gcg = new GClientGeocoder();
		gcg.getLatLng(_address, function(latlng){
			var lat = latlng.y;
			var lng = latlng.x;
			
			var api = 'http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=84e623faed4f8971&lat='+lat+'&lng='+lng+'&range=5&format=jsonp&callback=showResult&type=lite&count=25';
			
			var jsonp = new MyJSONP();
			jsonp.set(api);
			jsonp.get();
			
		});
		
	}, false);
}, false);

var showResult = function(obj) {
	var canvas = document.getElementById('shops');
	
	canvas.innerHTML = '<input type="button" value="距離順に戻す" style="display:none" id="bydistance"><input type="button" value="あなた好みに並べ替える" id="byscore">';
	
	scores = [];
	
	shops = obj.results.shop;

	for(var i = 0; i < shops.length; i++) {
		var shop = shops[i];

		var out = '';
		
		out += "<div class='shopinfo' id='shop"+i+"' style='margin-bottom:15px'>";
		out += "<div class='left' style='width:80px;text-align:center'><img src='"+shop.photo.pc.s+"'></div>";
		out += "<div class='left' style='width:500px'>";
		out += "  <div class='large' ><span id='shop"+i+"title'>"+shop.name+"</span></div>";
		out += "  <div class='middle' style='padding-left:5px'>"+shop['catch']+"</div>";
		out += "  <div class='small' style='padding-left:10px'>住所&nbsp;:&nbsp;"+shop.address+"</div>";


		out += "</div>";
		out += "<div class='right'><input type='button' class='showdetail' value='詳細' num='"+i+"'></div>";
		
		out += '<div class="clear"></div>';
		out += "</div>";
		out += '<div id="ad'+i+'"></div>';
		canvas.innerHTML += out;



		ys.push(document.getElementById('shop'+i).offsetTop);

		mc.classify(createSentenceForMachine(shop), i, function(id, ret) {
			var s = parseInt(ret);
			
			document.getElementById("shop"+id+'title').innerHTML += "&nbsp;&nbsp;<span style='font-size:small;font-weight:normal;color:gray'>("+s+")</span>";
			
			scores.push({id: id, score: s});
			
			if(s > 100)
				document.getElementById("shop"+id+'title').setAttribute('class', 'hot');
			else if(s > 50)
				document.getElementById("shop"+id+'title').setAttribute('class', 'cool');
			
			// スコアの計算が全て完了したらソートする
			if(scores.length == shops.length) {
				scores = scores.sort(function(a, b){return(a.score < b.score ? 1 : -1);});
			}
		});

	}

	
	var btns = document.getElementsByClassName('showdetail');
	
	for(var i = 0; i < btns.length; i++) {
		btns[i].addEventListener('click', showDetail, false);
	}
	
	document.getElementById('byscore').addEventListener('click', function(e) {
		this.style.display = 'none';
		document.getElementById('bydistance').style.display = 'block';
		for(var t = 0; t < scores.length; t++) {
			f = scores[t].id;
			rerank(f, t);
		}
	}, false);

	document.getElementById('bydistance').addEventListener('click', function(e) {
		this.style.display = 'none';
		document.getElementById('byscore').style.display = 'block';
		for(var f = 0; f < scores.length; f++) {
			rerank(f, f);
		}
	}, false);


};

var showDetail = function(e) {
	// グルメリストを隠す
	document.getElementById('shoplists').setAttribute('class', 'disappear');
	
	var that = this;
	
	// リストの回転が終わるのを待ってから処理
	window.setTimeout(function() {
		// 詳細画面を表示
		document.getElementById('shoplists').style.display = 'none';
		document.getElementById('detail').style.display = 'block';
		document.getElementById('detail').setAttribute('class', 'appear');

		// 配列要素番号の取得
		var num = that.getAttribute('num');
		var shop = shops[num];

		// 学習処理
		mc.like( createSentenceForMachine(shop) );
		
		// 店舗情報の表示
		var out = ''

		out += "<input type='button' id='back' value='戻る'><br />";

		out += "<div class='shopinfo' style='margin-bottom:15px'>";
		out += "<div class='left' style='width:200px;text-align:center'><img src='"+ shop.photo.pc.m +"'><br/><span class='small'>【画像提供：ホットペッパー　FooMoo】</span></div>";
		out += "<div class='left' style='width:450px'>";
		out += "<div class='large'><a href='"+shop.urls.pc+"' target='_blank'>"+shop.name+"</a></div>";
		out += "<div class='middle' style='padding-left:5px'>"+shop['catch']+"</div>";
		out += "<div class='small' style='padding-left:10px'>食事&nbsp;:&nbsp;"+shop.food.name+"</div>";
		out += "<div class='small' style='padding-left:10px'>ジャンル&nbsp;:&nbsp;"+shop.genre.name+"&nbsp;-&nbsp;"+shop.genre['catch']+"&nbsp;-</div>";
		out += "<div class='small' style='padding-left:10px'>住所&nbsp;:&nbsp;"+shop.address+"("+shop.access+")</div>";
		out += "</div>";
		out += '<div class="clear"></div>';
		out += "<div style='margin-left: 25px;margin-bottom: 150px;width:600px;height:350px;border: 1px solid gray;' id='map' class='reflect'>"+shop.lat+","+shop.lng+"</div>";
		out += "</div>";

		document.getElementById('shopdetail').innerHTML = out;

		// google mapの表示
		var map = new GMap2(document.getElementById('map'));
		var center = new GLatLng(shop.lat, shop.lng);
		map.setCenter(center, 17);
		
		map.addControl(new GLargeMapControl());
		
		var marker = new GMarker(center);
		map.addOverlay(marker);
		
		
		// ”戻る”ボタンがクリックされた時のハンドラ
		// 検索結果（リスト画面に戻る）
		document.getElementById('back').addEventListener('click', function(e) {
			// 詳細画面を隠す（回転）
			document.getElementById('detail').setAttribute('class', 'disappear');
			
			var that = this;
			
			// 回転が終わるのを待つ
			window.setTimeout(function() {
				// リスト画面を回転表示する。
				document.getElementById('detail').style.display = 'none';
				document.getElementById('shoplists').style.display = 'block';
				document.getElementById('shoplists').setAttribute('class', 'appear');
			}, 750);
		}, false);

	}, 750);
	
};

var rerank = function(from, to) {
	var from_y = ys[from];
	var to_y = ys[to];
	
	var dy = to_y - from_y;
	
	var t = document.getElementById('shop'+from);
	t.style.webkitTransition = '-webkit-transform 0.75s ease-in';
	t.offsetTop; // Force style recalc
    t.style.webkitTransformOrigin = "0 0";
    //t.style.webkitTransform = 'skew(30deg, 0deg) scale(0)';
    t.style.webkitTransform = 'translate(0, '+dy+'px)';
};


var createSentenceForMachine = function(shop) {
	return (shop.name + " " + shop['catch'] + " " + shop.food.name + " " + shop.genre.name + " " + shop.genre['catch']);
};

